var index = 0;
$(function(){
    $('#login-info').hide();
    $.ajax({
        url:'/exp6/Login',
        type:'GET',
        dataType:'json',
        success:function(data){
            if(data["state"]==1){
                var cookieuname=$.cookie("uname");
                $("#uname").text(cookieuname);
            }else {
                $.removeCookie('uname');
                $("#uname").replaceWith(`<a id="uname"  data-toggle="modal" data-target="#loginModel">登录</a>`);
            }
        }
    });
    getMessages(index,5);
})

function loadingMore() {
    index++;
    getMessages(index,5);
}

function login() {
    var name = $("#id").val();
    var password = $("#password").val();
    if(name=="" || password==""){
        $("#login-info").text("账号密码不可为空");
        $('#login-info').show();
        setTimeout(function(){$('#login-info').hide();},5000);
        return;
    }
    $.ajax({
        url:'/exp6/Login',
        type:'post',
        data:'id='+name+'&password='+password,
        dataType:'json',
        success:function(data){
            if(data["status"]==1){
                window.location.href = data["next"];
            }else {
                $("#login-info").text(data["info"]);
                $('#login-info').show();
                setTimeout(function(){$('#login-info').hide();},5000);
            }
        }
    });
}

function getMessages(page, limit) {
    var postdata = {"data":"MessageByPage","page":page, "limit":limit};
    $.ajax({
        url:'/exp6/Note',
        type:'GET',
        data:postdata,
        dataType:'json',
        success:function(data){
            if(data["status"]==1){
                var messages = data["list"];
                $("#loadinggif").remove();
                for(var i=0; i<messages.length; i++) {
                    addMessageDiv(messages[i]);
                }
                if(messages.length<5){
                    $(".endtag button").hide();
                    $(".endtag").append("<h4 class='text-info'>到底了~</h4>");
                }
            }
        }
    });
}

function addMessageDiv(message) {
    var mID = message.messageID;
    let tpl =
        `<div class="media">
        <div class="media-left"><span class="glyphicon glyphicon-user"></span></div>
        <div id="${"mID-"+mID}" class="media-body">
            <h4 class="media-heading"><small>${message.writer}<i>  发布于 ${message.writerDate}</i></small></h4>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"><strong id="${"mID-"+mID+"_title"}">${message.title}</strong>
                        <small id="${"mID-"+mID+"_more"}" style="cursor:pointer" onclick="getRevert(${mID})" class="btn-xs pull-right">查看回复(${message.count})</small>
                    </h3>
                </div>
                <div id="${"mID-"+mID+"_content"}" class="cont panel-body">${message.content.replace(new RegExp("\n", 'g'),"<br>")}</div>
            </div>
        </div>
    </div>`;

    $("#showNote").append(tpl);
    var moreTag = $("#mID-"+mID+"_more");
    var cookieUname = $.cookie('uname');
    if(cookieUname){
        moreTag.after(`<small id="${"mID-"+mID+"_ret"}" style="cursor:pointer" onclick="addRevert(${mID},'${message.writer}')" class="btn-xs pull-right">回复</small>`);
        if(cookieUname == message.writer){
            moreTag.after(`<small id="${"mID-"+mID+"_edit"}" style="cursor:pointer" onclick="updateMessage(${mID})" class="btn-xs pull-right">编辑</small>
                           <small id="${"mID-"+mID+"_del"}" style="cursor:pointer" onclick="deleteMessage(${mID})" class="btn-xs pull-right">删除</small>`);
        }
    }
}

function getRevert(mID) {
    if($("#mID-"+mID+"_hide").val()=="" || $("#mID-"+mID+"_more").html().replace(/.*\((\d+)\)$/, '$1')=="0") return;
    var postdata = {"data":"Revert","messageID":mID};
    $.ajax({
        url:'/exp6/Note',
        type:'GET',
        data:postdata,
        dataType:'json',
        success:function(data){
            if(data["status"]==1){
                var reverts = data["list"];
                for(var i=0; i<reverts.length; i++) {
                    addRevertDiv(reverts[i], mID);
                }
                $("#mID-"+mID+"_more").after(`<small id='${"mID-"+mID+"_hide"}' style="cursor:pointer" onclick="hiddenReverts(${mID})" class="btn-xs pull-right">收起</small></h3>`);
            }
        }
    });
}

function hiddenReverts(mID) {
    $("#mID-"+mID+" .media").remove();
    $("#mID-"+mID+"_hide").remove();
}

function addRevertDiv(revert,mID) {
    var rID = revert.revertID;
    let tpl =
        `<div class="media">
        <div class="media-left"><span class="glyphicon glyphicon-chevron-right"></span></div>
        <div id="${"rID-"+rID}" class="media-body">
            <h4 class="media-heading"><small><span class="glyphicon glyphicon-user"></span> ${revert.writer}<i>  发布于 ${revert.writerDate}</i></small></h4>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"><strong><span class="glyphicon glyphicon-comment"></span></strong>
                    </h3>
                </div>
                <div id="${"rID-"+rID+"_content"}" class="cont panel-body">${revert.content.replace(new RegExp("\n", 'g'),"<br>")}</div>
            </div>
        </div>
    </div>`;
    $("#mID-"+mID).append(tpl);
    var cookieUname = $.cookie('uname');
    if(cookieUname == revert.writer){
        $("#rID-"+rID+" .panel-title").append(
            `<small id="${"rID-"+rID+"_edit"}" style="cursor:pointer" onclick="updateRevert(${rID},${mID})" class="btn-xs pull-right">编辑</small>
            <small id="${"rID-"+rID+"_del"}" style="cursor:pointer" onclick="deleteRevert(${rID})" class="btn-xs pull-right">删除</small>`);
    }
}

function afterOperate(data) {
    if(data["status"]==1){
        if(data["flag"]==1){
            $("#showNote").empty();
            index = 0;
            $(".endtag button").show();
            $(".endtag h4").remove();
            getMessages(index,5);
        }else {
            alert("操作失败，请重试");
        }
    }else {
        alert(data["info"]);
    }
}

function addMessage() {
    var cookieUname = $.cookie('uname');
    if(cookieUname){
        var mtitle = $("#addMessageTitle").val();
        var mcontent = $("#addMessageContent").val();
        if(mtitle=="" && mcontent=="") return;
        if(mtitle.length>25){
            alert("当前标题长度为"+mtitle.length+"，标题长度不得超过25字符");
            return;
        }
        var postdata = {
            "operate":"addMessage",
            "title":mtitle,
            "content":mcontent,
            "writer":cookieUname,
            "writeDate":getDate(),
            "count": 0};

        $.ajax({
            url:'/exp6/Note',
            type:'POST',
            data:postdata,
            dataType:'json',
            success:function(data){
                afterOperate(data);
                $("#addMessageTitle").val("");
                $("#addMessageContent").val("");
            }
        });
    }else{
        $('#loginModel').modal('show');
    }
}

function addRevert(mID, mwriter) { // TODO: addRevert
    let tpl =
        `<div class="media">
            <div class="media-left"><span class="glyphicon glyphicon-chevron-right"></span></div>
            <div class="media-body">
                <h4 class="media-heading"><span class="glyphicon glyphicon-user"></span> ${$.cookie('uname')}</h4>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title"><strong><span class="glyphicon glyphicon-comment"></span></strong>
                        </h3>
                    </div>
                    <div class="panel-body"><textarea id="${"add-"+mID+"_content"}" placeholder="回复${mwriter}" class="form-control" rows="4"></textarea></div>
                </div>
            </div>
        </div>
        <input type="button" onclick="submitAddRevert(${mID})" class="btn-sm btn-danger pull-right" value="回复">&nbsp;
        <input type="button" onclick="cancel()" class="btn-sm btn-danger pull-right" value="取消">`;
    $("#mID-"+mID+"_content").parent().after(tpl);
}

function submitAddRevert(mID) {
    var mcontent = $("#add-"+mID+"_content").val();
    if(mcontent=="") return;
    var postdata = {
        "operate":"addRevert",
        "messageID":mID,
        "content":mcontent,
        "writer":$.cookie('uname'),
        "writeDate":getDate()};

    $.ajax({
        url:'/exp6/Note',
        type:'POST',
        data:postdata,
        dataType:'json',
        success:function(data){
            afterOperate(data)
        }
    });
}

function deleteMessage(mID) {
    $.ajax({
        url:'/exp6/Note',
        type:'POST',
        data: {"operate":"deleteMessage","messageID":mID},
        dataType:'json',
        success:function(data){
            afterOperate(data)
        }
    });
}

function updateMessage(mID) {
    var titleTag = $("#mID-"+mID+"_title");
    var contentTag = $("#mID-"+mID+"_content");
    var mcontent = contentTag.html();
    var mtitle = titleTag.text();
    titleTag.replaceWith(`<input id="${"mID-"+mID+"_title"}" type="text" class="form-control" value="${mtitle}">`);
    contentTag.empty();
    contentTag.append(`<textarea class="form-control" rows="${strCharPosition(mcontent,"<br>")+3}">${mcontent.replace(new RegExp("<br>", 'g'),"\n")}</textarea>`);
    contentTag.append(`<input type="button" onclick="cancel()" class="btn-sm btn-danger pull-right" value="取消">&nbsp;`);
    contentTag.append(`<input type="button" onclick="submitUpdateMessage(${mID})" class="btn-sm btn-danger pull-right" value="修改">`);
    $("#mID-"+mID+"_more").hide();
    $("#mID-"+mID+"_edit").hide();
    $("#mID-"+mID+"_del").hide();
    $("#mID-"+mID+"_ret").hide();
}

function getDate() {
    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
    var time = new Date().Format("yyyy-MM-dd hh:mm:ss");
    return time.toString();
}

function submitUpdateMessage(mID) {
    var mtitle = $("#mID-"+mID+"_title").val();
    if(mtitle.length>25){
        alert("当前标题长度为"+mtitle.length+"，标题长度不得超过25字符");
        return;
    }
    var mcontent = $("#mID-"+mID+"_content textarea").val();
    if(mtitle==""&&mcontent=="") return;
    var postdata = {"operate":"updateMessage",
                    "messageID":mID,
                    "title":mtitle,
                    "content":mcontent,
                    "writer":$.cookie('uname'),
                    "writeDate":getDate(),
                    "count": $("#mID-"+mID+"_more").html().replace(/.*\((\d+)\)$/, '$1')};
    $.ajax({
        url:'/exp6/Note',
        type:'POST',
        data:postdata,
        dataType:'json',
        success:function(data){
            afterOperate(data)
        }
    });
}

function cancel() {
    $("#showNote").empty();
    index = 0;
    getMessages(index,5);
}

function deleteRevert(rID) {
    $.ajax({
        url:'/exp6/Note',
        type:'POST',
        data: {"operate":"deleteRevert","revertID":rID},
        dataType:'json',
        success:function(data){
            afterOperate(data)
        }
    });
}

function updateRevert(rID,mID) {
    var contentTag = $("#rID-"+rID+"_content");
    var rcontent = contentTag.html();
    contentTag.empty();
    contentTag.append(`<textarea class="form-control" rows="${strCharPosition(rcontent,"<br>")+3}">${rcontent.replace(new RegExp("<br>", 'g'),"\n")}</textarea>`);
    contentTag.after(`<input type="button" onclick="cancel()" class="btn-sm btn-danger pull-right" value="取消">&nbsp;`);
    contentTag.after(`<input type="button" onclick="submitUpdateRevert(${rID},${mID})" class="btn-sm btn-danger pull-right" value="修改">`);

    $("#rID-"+rID+"_edit").hide();
    $("#rID-"+rID+"_del").hide();
}

function submitUpdateRevert(rID,mID){
    var rcontent = $("#rID-"+rID+"_content textarea").val();
    if(rcontent=="") return
    var postdata = {
        "operate":"updateRevert",
        "messageID":mID,
        "revertID":rID,
        "content":rcontent,
        "writer":$.cookie('uname'),
        "writeDate":getDate()};

    $.ajax({
        url:'/exp6/Note',
        type:'POST',
        data:postdata,
        dataType:'json',
        success:function(data){
            afterOperate(data)
        }
    });
}

function searchByKeyWord() {
    var keyWord = $("#searchword").val();
    if(keyWord=="") return
    var postdata = {"data":"Search","keyWord":keyWord};
    $.ajax({
        url:'/exp6/Note',
        type:'GET',
        data: postdata,
        dataType:'json',
        success:function(data){
            if(data["status"]==1){
                $("#showNote").empty();
                var messages = data["list"];
                var len = messages.length;
                if(len==0){
                    $("#showNote").append("<h3 align=\"center\">未查询到相关信息</h3>");
                }
                for(var i=0; i<len; i++) {
                    messages[i].content=messages[i].content.replace(new RegExp(postdata.keyWord, 'g'),"<strong style='color: red'>"+postdata.keyWord+"</strong>");
                    addMessageDiv(messages[i]);
                    var mID = messages[i].messageID;
                    rets = messages[i].list;
                    for(var j=0;j<rets.length;j++){
                        if(rets[j].content.indexOf(postdata.keyWord)>-1){
                            rets[j].content=rets[j].content.replace(new RegExp(postdata.keyWord, 'g'),"<strong style='color: red'>"+postdata.keyWord+"</strong>");
                            addRevertDiv(rets[j], mID);
                        }
                    }
                    $("#mID-"+mID+"_more").after(`<small id='${"mID-"+mID+"_hide"}' style="cursor:pointer" onclick="hiddenReverts(${mID})" class="btn-xs pull-right">收起</small></h3>`);
                }
                $(".endtag").empty();
            }
        }
    });
}

//检测一个字符在字符串中出现次数，参数字符串，一个字符，返回字符串出现的次数
function strCharPosition(str, char) {
    var pos;
    var arr = [];
    pos = str.indexOf(char);
    while (pos > -1) {
        arr.push(pos);
        pos = str.indexOf(char, pos + 1);
    }
    return arr.length;
}

// $(window).scroll(function () {
//     var scrollTop = $(this).scrollTop();
//     var docHeight = $(document).height();
//     var screenHeight = window.screen.availHeight;
//     if((scrollTop + screenHeight) >= docHeight-80) {// 已滑到底部 加载数据
//         loadingMore()
//     }
// })